package it.uniroma2.util.tree;

import java.util.Random;

public class RandomTreeGenerator {
	
	public RandomTreeGenerator() {
		this(0);
	}
	
	public RandomTreeGenerator(int seed) {
		rand = new Random(seed);
	}
	
	public String[] symbols = new String[] {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
	public Random rand;
	
	public String generateRandomTree(int labels, int maxWidth, int nodes) {
		if (labels > symbols.length || nodes < 2) {
			System.out.println("Error!");
			return "";
		}
		String tree = "("+symbols[rand.nextInt(labels)]+" ";
		nodes--;
		int maxSubtrees = Math.min(maxWidth, nodes/2);
		if (maxSubtrees == 0)
			//Terminals and non-terminals must be different
			tree += symbols[rand.nextInt(labels)].toLowerCase();
		else {
			int subtrees = rand.nextInt(maxSubtrees)+1;
			for (int i=subtrees-1; i>=0; i--) {
				int childNodes = i==0 ? nodes : rand.nextInt(nodes - i*2 - 1) + 2;
				tree += generateRandomTree(labels, maxWidth, childNodes);
				nodes = nodes - childNodes;
			}
		}
		tree += ")";
		return tree;
	}

	public String[] getSymbols() {
		return symbols;
	}

	public void setSymbols(String[] symbols) {
		this.symbols = symbols;
	}

}
